﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Messaging;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ComTools
{
    public partial class frmSendPost : Form
    {
        public frmSendPost()
        {
            InitializeComponent();
        }

        private void FrmSendPost_Load(object sender, EventArgs e)
        {
            string path = textBox1.Text.Trim();
            if (!MessageQueue.Exists(path))
            {
                messageQueue = MessageQueue.Create(path);
            }
            else
            {
                messageQueue = new MessageQueue(path);
            }
            messageQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(MsgParam) });
            messageQueue.Formatter = new BinaryMessageFormatter();

            messageQueue.ReceiveCompleted += MessageQueue_ReceiveCompleted;
            //
            txtContent.Text = Newtonsoft.Json.JsonConvert.SerializeObject(new MsgParam()
            {
                ExtNumCode = "A001",
                ExtNumName = "A001",
                EntityFullName = "UFIDA.U9.SM.SOLINE",
                EntityKey = 111111
            });
        }

        MessageQueue messageQueue = null;

        private void MessageQueue_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
        {
            var message = messageQueue.EndReceive(e.AsyncResult);
            new MethodInvoker(() => {
                var msg = message.Body as MsgParam;
                var xx = Newtonsoft.Json.JsonConvert.SerializeObject(msg);
                textBox2.AppendText(xx);
            }).BeginInvoke(null, null);
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            string content = txtContent.Text.Trim();
            MsgParam msgP = Newtonsoft.Json.JsonConvert.DeserializeObject<MsgParam>(content);
            //
            messageQueue.Send(msgP);
        }

        private void btnReceive_Click(object sender, EventArgs e)
        {
            var iasync = messageQueue.BeginReceive();
        }
    }
    [Serializable()]
    class MsgParam
    {
        /// <summary>
        /// 需求分类代码
        /// </summary>
        public string ExtNumCode { get; set; }
        /// <summary>
        /// 颥求分类名称
        /// </summary>
        public string ExtNumName { get; set; }
        /// <summary>
        /// 实体全名
        /// </summary>
        public string EntityFullName { get; set; }
        /// <summary>
        /// 实体主键
        /// </summary>
        public long EntityKey { get; set; }
    }
}
